//
//  EPCMainController.swift
//  Weibo
//
//  Created by LioWu on 01/04/2017.
//  Copyright © 2017 MyGit. All rights reserved.
//

import UIKit
import SVProgressHUD

class EPCMainController: UITabBarController {

    fileprivate var timer:Timer?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupChildControllers()
        
        setupComposeButton()
        
        setupNewFeatureViews()
        
        setupTimer()
        
        delegate = self
        
        NotificationCenter.default.addObserver(self, selector: #selector(userLogin), name: NSNotification.Name(rawValue: EPCUserShouldLoginNotification), object: nil)
    }

    @objc fileprivate func composeStatus() {
    
    }
    
    lazy var composeButton: UIButton = UIButton.cz_imageButton("tabbar_compose_icon_add", backgroundImageName: "tabbar_compose_button")
    
    
    deinit {
        timer?.invalidate()
    }
    
    @objc private func userLogin(no:Notification) {
        
        var when = DispatchTime.now()
        if no.object != nil {
            when = DispatchTime.now() + 2
            
            SVProgressHUD.setDefaultMaskType(.black)
            SVProgressHUD.showInfo(withStatus: "用户登录已超时，请重新登录")
        }
        
        DispatchQueue.main.asyncAfter(deadline: when) {
            
            SVProgressHUD.setDefaultMaskType(.clear)
            
            let OAuthNav = UINavigationController.init(rootViewController: EPCOAuthController())
            self.present(OAuthNav, animated: true, completion: nil)
        }
    }
    
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .portrait
    }
}


// MARK: - timer
extension EPCMainController {

    func setupTimer() {
        timer = Timer.scheduledTimer(timeInterval: 30.0, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
    }
    
    func updateTimer() {
        
        if EPCNetworking.shareManager.userLogon == false {
            return
        }
        
        EPCNetworking.shareManager.unreadCount { (unreadCount) in
            print("监测到\(unreadCount)条新微博")
            
            self.tabBar.items?[0].badgeValue = unreadCount > 0 ? "\(unreadCount)" : nil
            
            UIApplication.shared.applicationIconBadgeNumber = unreadCount
        }
    }
}


// MARK: - new featrue / welcome
extension EPCMainController {
    
    fileprivate func setupNewFeatureViews() {
        
        if EPCNetworking.shareManager.userLogon == false {
            return
        }
        
        let v = isNewVersion ? EPCNewFeatureView.newFeatureView() : EPCWelcomeView.welcomeView()
        
        v.frame = view.bounds
        
        view.addSubview(v)
    }
    
    private var isNewVersion:Bool {
        
        // print(Bundle.main.infoDictionary)
        
        // 1. current version
        let currentVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? ""
        print("当前版本\(currentVersion)")
        
        // 2. last version
        let path:String = ("version" as NSString).cz_appendDocumentDir()
        let sandBox = (try? String.init(contentsOfFile: path)) ?? ""
        print("沙盒版本\(sandBox)")
        
        // 3. save currentVersion to local
        _ = try? currentVersion.write(toFile: path, atomically: true, encoding: .utf8)
        
        return currentVersion != sandBox
    }
}


// MARK: - UITabBarControllerDelegate
extension EPCMainController: UITabBarControllerDelegate {
    
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        
        let idx = viewControllers?.index(of: viewController)
        if selectedIndex == 0 && idx == selectedIndex {
            
            let nav = viewController as! EPCNavgitionController
            let vc = nav.childViewControllers[0] as! EPCHomeController
            
            vc.tableView?.setContentOffset(CGPoint.init(x: 0, y: -64), animated: true)
            
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5, execute: {
                vc.loadData()
            })
            
            // 清除badge
            vc.tabBarItem.badgeValue = nil
            UIApplication.shared.applicationIconBadgeNumber = 0
        }
        
        let shouldChange = viewController.isMember(of: UIViewController.self) ? false : true
        
        return shouldChange
    }
    
    func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
        
    }
}


// MARK: - ChildController
extension EPCMainController {
    
    fileprivate func setupChildControllers() -> () {
        
        // 1.sandBox 2.mainBundle
        let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let jsonPath = docDir.appending("/" + "main.json")
        
        var data = NSData.init(contentsOfFile: jsonPath)
        
        if data == nil  {
            let path = Bundle.main.path(forResource: "main.json", ofType: nil)
            data = NSData.init(contentsOfFile: path!)
        }
        
        guard let array = try? JSONSerialization.jsonObject(with: data! as Data, options: .allowFragments) as? [[String: Any]] else {
                return
        }
        
        /*
        let array: [[String:Any]] =
        [["clsName": "EPCHomeController",
          "title": "首页",
          "imageName": "home",
          "visitorInfo":["imageName": "",
                         "message": "登录看首页，登录看首页，登录看首页，登录看首页，登录看首页"]],
         
         ["clsName": "EPCMessageController",
          "title": "消息",
          "imageName": "message_center",
          "visitorInfo":["imageName": "visitordiscover_image_message",
                         "message": "登录看消息，登录看消息，登录看消息，登录看消息"]],
         
         ["clsName": "UIViewController"],
         
         ["clsName": "EPCDiscoverController",
          "title": "发现",
          "imageName": "discover",
          "visitorInfo":["imageName": "visitordiscover_image_message",
                         "message": "发现，发现"]],
         
         ["clsName": "EPCProfileController",
          "title": "我",
          "imageName": "profile",
          "visitorInfo":["imageName": "visitordiscover_image_profile",
                         "message": "登录查看个人信息，登录查看个人信息，登录查看个人信息，登录查看个人信息，登录查看个人信息，登录查看个人信息，登录查看个人信息，"]],
         ]
        */
        
        // array -> plist
    // (array as NSArray).write(toFile: "/Users/wulinfeng/Desktop/originSetting.plist", atomically: true)

        // array -> json
    //        if let data = try? JSONSerialization.data(withJSONObject: array, options: .prettyPrinted) {
    //            (data as NSData).write(toFile: "/Users/wulinfeng/Desktop/main.json", atomically: true)
    //        }
        
        
        var vcArray = [UIViewController]()
        
        for i in array! {
            
            vcArray.append(childController(dict: i))
        }
        
        self.viewControllers = vcArray
    }
    
    
    /// setting compose button
    fileprivate func setupComposeButton() {
        
        tabBar.addSubview(composeButton)
        
        let count = CGFloat(childViewControllers.count)
        
        // tabbarItem width, ‘ - 1 ’ 是为了遮挡容错点
        // let w = tabBar.bounds.width / count + 5
        
        // tabbarItem width, UITabBarControllerDelegate解决了上面问题
        let w = tabBar.bounds.width / count
        
        composeButton.frame = tabBar.bounds.insetBy(dx: 2 * w, dy: 0)
        
        composeButton.addTarget(self, action: #selector(composeStatus), for: .touchUpInside)
    }
    
    /// Create a controller with dictionary
    ///
    /// - Parameter dict: dictionary, ["clsName": "", "title": "", "imageName": "", "visitorInfo": []]
    /// - Returns: UIViewController
    private func childController(dict: [String: Any]) -> UIViewController {
        
        guard let clsName = dict["clsName"] as? String,
            let title = dict["title"] as? String,
            let imageName = dict["imageName"] as? String,
            let cls = NSClassFromString(Bundle.main.namespace + "." + clsName) as? EPCBaseTableController.Type,
            let visitorInfo = dict["visitorInfo"] as? [String: String]
            else {
                
                return UIViewController()
        }
        
        // init controller
        let vc = cls.init()
        
        vc.title = title
        
        vc.visitorInfoDict = visitorInfo
        
        // set tabBarItem image/selectedImage
        vc.tabBarItem.image = UIImage.init(named: "tabbar_\(imageName)")
        
        vc.tabBarItem.selectedImage = UIImage.init(named: "tabbar_\(imageName)_selected")?.withRenderingMode(.alwaysOriginal)
        
        // set tabBarItem text attribute
        vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.orange], for: .selected)
        
        vc.tabBarItem.setTitleTextAttributes([NSFontAttributeName: UIFont.systemFont(ofSize: 11)], for: .normal)
        
        let nav = EPCNavgitionController.init(rootViewController: vc)
        
        return nav
    }
}
